package com.kkb.shopcenter.server.impl;

import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kkb.shopcenter.api.TemplateInfoService;
import com.kkb.shopcenter.common.pojo.BrandInfo;
import com.kkb.shopcenter.common.pojo.TemplateInfo;
import com.kkb.shopcenter.server.mappers.BrandInfoMapper;
import com.kkb.shopcenter.server.mappers.TemplateInfoMapper;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TemplateInfoServiceImpl implements TemplateInfoService {

    @Autowired
    private TemplateInfoMapper templateInfoMapper;

    @Autowired
    private BrandInfoMapper brandInfoMapper;

    @Override
    public PageInfo<TemplateInfo> getTemplate(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        List<TemplateInfo>  templateInfos = templateInfoMapper.selectAll();
        PageInfo<TemplateInfo> pageInfo = new PageInfo<>(templateInfos);
        return pageInfo;
    }

    @Override
    public int updateTemplateInfo(TemplateInfo record) {
        //获取品牌ID集合
        String brandids = record.getBrands();
        //判断品牌ID集合是否为空
        if(StringUtils.isNotEmpty(brandids)){
            String[] brandidarray = StringUtils.split(brandids,',');
            List<Map<String,Object>> result = new ArrayList<>();
            for(String brandid: brandidarray){
                //封装品牌ID和名称对象
                Map<String,Object> brand = new HashMap<>();
                int id = NumberUtil.parseInt(brandid);
                BrandInfo brandInfo =brandInfoMapper.selectByPrimaryKey(id);
                brand.put("brandName",brandInfo.getBrandName());
                brand.put("id",id);
                result.add(brand);
            }
            //转换成JSON格式字符串，设置品牌属性
           record.setBrands(JSONArray.toJSONString(result));
        }
        return templateInfoMapper.updateByPrimaryKeySelective(record);

    }

    @Override
    public TemplateInfo getBrandsAndAttr(Long id) {
        return templateInfoMapper.selectByPrimaryKey(id);
    }


}
